﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebChat.User
{
    public partial class ConfirmDeleteMessage : System.Web.UI.Page
    {
        WebChatDAL.WebChatDAO dao = new WebChatDAL.WebChatDAO();

        protected void Page_Load(object sender, EventArgs e)
        {
            this.ButtonDelete.Visible = false;
            string messageIdString  = Request["messageId"];

            int messageId;
            if (!Int32.TryParse(messageIdString, out messageId))
            {
                this.LabelInfo.Text = "invalid message id";
                return;
            }
            
            string messageContent;
            if(!dao.TryGetChannelMessageContentByMessageId(messageId, out messageContent))
            {
                this.LabelInfo.Text = "could not find this message in the database";
                return;
            }

            this.LabelMessage.Text = Server.HtmlEncode(messageContent);
            this.LabelInfo.Text = "Are you sure you want to delete this message?";
            this.ButtonDelete.Visible = true;
        }

        protected void ButtonDelete_OnClick(object sender, EventArgs e)
        {
            this.ButtonDelete.Visible = false;
            string messageIdString = Request["messageId"];

            int messageId;
            if (!Int32.TryParse(messageIdString, out messageId))
            {
                this.LabelInfo.Text = "invalid message id";
                return;
            }
                        
            string messageContent;
            if (!dao.TryGetChannelMessageContentByMessageId(messageId, out messageContent))
            {
                this.LabelInfo.Text = "could not find this message in the database";
                return;
            }

            if (!dao.TryDeleteChannelMessageByMessageId(messageId, Page.User.Identity.Name))
            {
                this.LabelInfo.Text = "Could not delete message!";
                return;
            }

            Response.Redirect("MessageDeleteSuccess.aspx");
        }
    }
}